<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>用户管理</title>
    <!--引入vue.js库-->
    <!-- <script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script> -->
    <script src="/js/vue.js"></script>
    <!-- element-ui引入样式 -->
    <link rel="stylesheet" href="/css/index.css">
    <!-- element-ui引入组件库 -->
    <script src="/js/index.js"></script>
    <!--引入axios库-->
    <!-- <script src="https://unpkg.com/axios/dist/axios.min.js"></script>-->
    <script src="/js/axios.min.js"></script>
    <style>
        .avatar-uploader .el-upload {
            border: 1px dashed #d9d9d9;
            border-radius: 6px;
            cursor: pointer;
            position: relative;
            overflow: hidden;
        }
        .avatar-uploader .el-upload:hover {
            border-color: #409EFF;
        }
        .avatar-uploader-icon {
            font-size: 28px;
            color: #8c939d;
            width: 178px;
            height: 178px;
            line-height: 178px;
            text-align: center;
        }
        .avatar {
            width: 178px;
            height: 178px;
            display: block;
        }
    </style>
</head>
<body>
<div id="app">
    <!-- 根据参数查询 和 添加数据 -->
    <el-row>
        <el-col :span="4">
            <el-input v-model="searchForm.loginName" placeholder="请输入登录账号"></el-input>
        </el-col>
        <el-col :span="4">
            <el-input v-model="searchForm.userName"  placeholder="请输入用户昵称"></el-input>
        </el-col>
        <el-col :span="4">
            <el-input v-model="searchForm.phonenumber" placeholder="请输入手机号码"></el-input>
        </el-col>
        <el-col :span="6">
            <el-button type="success" icon="el-icon-search" @click="search">搜索</el-button>
            <el-button type="primary" icon="el-icon-plus" @click="handleAdd">添加</el-button>
            <el-button type="primary" icon="el-icon-refresh" @click="refresh">刷新</el-button>
        </el-col>
        <el-col :span="6"></el-col>
    </el-row>

    <!-- 查询的数据指定数据 -->
    <el-table :data="tableData" border style="width: 100%">

        <el-table-column
                align="center"
                width="100"
                prop="loginName"
                label="用户昵称">
        </el-table-column>
        <el-table-column label="用户头像" width="160" height="120">
                    <template slot-scope="scope">
                        <el-image
                                style="width: 80px; height: 80px"
                                :src="scope.row.avatar"
                        ></el-image>
                    </template>
                </el-table-column>
        <el-table-column
                align="center"
                width="100"
                prop="userName"
                label="登陆账号">
        </el-table-column>
        <el-table-column
                align="center"
                width="100"
                prop="userType"
                :formatter="getStatus1"
                label="用户类型">
        </el-table-column>
        <el-table-column
                align="center"
                width="200"
                prop="email"
                label="用户邮箱">
        </el-table-column>
        <el-table-column
                align="center"
                width="200"
                prop="phonenumber"
                label="手机号码">

        </el-table-column>
        <el-table-column
                align="center"
                width="100"
                prop="sex"
                :formatter="getStatus2"
                label="用户性别">
        </el-table-column>
        <el-table-column
                align="center"
                width="100"
                prop="status"
                :formatter="getStatus3"
                label="账号状态">
        </el-table-column>
        <el-table-column
                align="center"
                width="100"
                prop="delFlag"
                :formatter="getStatus4"
                label="删除标志">
        </el-table-column>
        <el-table-column
                align="center"
                width="200"
                prop="loginIp"
                label="最后登录IP">
        </el-table-column>
        <el-table-column
                align="center"
                width="201"
                prop="loginDate"
                label="最后登录时间"></el-table-column>
        <el-table-column
                align="center"
                width="99"
                prop="createBy"
                label="创建者"></el-table-column>
        <el-table-column
                align="center"
                width="201"
                prop="createTime"
                label="创建时间"></el-table-column>
        <el-table-column
                align="center"
                width="99"
                prop="updateBy"
                label="更新者"></el-table-column>
        <el-table-column align="center" width="200" prop="updateTime" label="更新时间"></el-table-column>
        <el-table-column align="center" width="200" prop="remark" label="备注"></el-table-column>

        <el-table-column fixed="right" width="300" label="操作" width="140">
            <template slot-scope="scope">
                <el-button
                        size="mini" type="success" @click="handleRole(scope.$index, scope.row)">授予角色
                </el-button>
                <el-button
                        size="mini"
                        type="primary"
                        @click="handleEdit(scope.$index, scope.row)">编辑
                </el-button>
                <el-button size="mini" type="danger" @click="deleteDept(scope.row)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>

    <!-- 分页功能 -->
    <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[3,6, 12, 24, 120]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total">
    </el-pagination>

    <!--    添加修改弹窗-->
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
        <el-form :model="form" :rules="rules" ref="ruleForm">
            <!-- 照片墙
     action：''填写上传到后台的接口
     list-type：文件列表的类型（我选的是照片墙）
     limit：最大允许上传个数
     show-file-list：是否显示已上传文件列表
     auto-upload：是否在选取文件后立即进行上传
     on-change：文件状态改变时的钩子，添加文件、上传成功和上传失败时都会被调用
     multiple：是否支持多选文件-->

            <el-form-item label="用户昵称" :label-width="formLabelWidth" prop="empName">
                <el-input v-model="form.loginName" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="登陆账号" :label-width="formLabelWidth" prop="sex">
                <el-input v-model="form.userName" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="头像" :label-width="formLabelWidth">
                <!--上传图片  -->
                <el-upload
                        class="avatar-uploader"
                        action="/user/uploadFile"
                        name="file1"
                        :show-file-list="false"
                        :on-success="handleFileSuccess"
                        :before-upload="beforeFileUpload">
                    <img v-if="imageUrl" :src="imageUrl" class="avatar">
                    <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
            </el-form-item>
            <el-form-item label="用户类型" :label-width="formLabelWidth" prop="phoneNum">
                <el-select v-model="form.userType" placeholder="请选用户类型">
                    <el-option label="系统用户" value="0"></el-option>
                    <el-option label="非系统用户" value="1"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="用户邮箱" :label-width="formLabelWidth" prop="province">
                <el-input v-model="form.email"placeholder="请选输入邮箱"></el-input>
            </el-form-item>
            <el-form-item label="手机号码" :label-width="formLabelWidth" prop="hireDate">
                <el-input v-model="form.phonenumber" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="用户性别" :label-width="formLabelWidth" prop="hireDate">
                <el-select v-model="form.sex" placeholder="请选用户性别">
                    <el-option label="男" value="0"></el-option>
                    <el-option label="女" value="1"></el-option>
                </el-select>
            </el-form-item>
<!--            <el-form-item label="头像路径" :label-width="formLabelWidth" prop="salary">-->
<!--                <el-input v-model="form.avatar" autocomplete="off"></el-input>-->
<!--            </el-form-item>-->
<!--            <el-form-item label="密码" :label-width="formLabelWidth" prop="password">-->
<!--                <el-input v-model="form.password" autocomplete="off"></el-input>-->
<!--            </el-form-item>-->
<!--            <el-form-item label="盐加密" :label-width="formLabelWidth" prop="password">-->
<!--                <el-input v-model="form.salt" autocomplete="off"></el-input>-->
<!--            </el-form-item>-->
            <el-form-item label="账号状态" :label-width="formLabelWidth" prop="password">
                <!--  下拉框 -->
                <el-select v-model="form.status" placeholder="请选择账号状态">
                    <el-option label="正常" value="0"></el-option>
                    <el-option label="停用" value="1"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="删除标志" :label-width="formLabelWidth" prop="password">
                <el-select v-model="form.delFlag" placeholder="请选择删除标志">
                    <el-option label="存在" value="0"></el-option>
                    <el-option label="删除" value="2"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="备注" :label-width="formLabelWidth" prop="password">
                <el-input v-model="form.remark" autocomplete="off"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="addOrUpdate">确 定</el-button>
        </div>
    </el-dialog>

    <!--授予角色表单-->
    <el-dialog
            title="角色列表"
            :visible.sync="dialogVisible"
            width="30%">
        <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
        <div style="margin: 15px 0;"></div>
        <el-checkbox-group v-model="checkedRoles" @change="handleCheckedRolesChange">
            <el-checkbox v-for="role in roleList" :label="role.roleId" :key="role.roleId">{{role.roleName}}
            </el-checkbox>
        </el-checkbox-group>
        <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addUserAndRole">确 定</el-button>
  </span>
    </el-dialog>
</div>
<script>
    var vue = new Vue({
        el: '#app',
        data() {
            return {
                tableData: [],//表格数据
                currentPage: 1,//页码
                pageSize: 3,//每页显示的数量
                total: 100,//分页总数量
                searchForm: {loginName: '', userName: '', phonenumber: ''},//查询携带的参数
                dialogFormVisible: false, //使弹出不显示
                title: '用户添加', //title 默认为 用户添加
                //添加或者更新数据时 携带的参数
                form: {},
                //弹出框的宽度
                formLabelWidth: '120px',

                //角色弹出框设置
                dialogVisible: false,//角色授权表 取消授权  //不显示角色列表对话框
                checkAll: false,  //是否全选
                checkedRoles: [],  //默认选中的角色
                roleList: [], //有效角色集合
                roleIds: "",//定义所有中的所选角色id集合
                isIndeterminate: true,
                tempUserId: 0, //用户id
                //结束
                imageUrl:'',//上传照片设置
            }
        },
        //加载时默认执行的方法
        created: function () {
            //调用封装的方法
            this.loadData();
            this.getHaveRole();
        },
        methods: {//定义变量_this等于外面的this
            //封装请求数据的方法
            loadData() {
                var _this = this;
                axios.post('/user/queryPage', {
                    pageNo: this.currentPage,
                    pageSize: this.pageSize,
                    data: {
                        "loginName": this.searchForm.loginName, "userName": this.searchForm.userName,
                        "phonenumber": this.searchForm.phonenumber
                    }
                })
                    .then(function (response) {
                        console.log(response);
                        //判断是否执行成功
                        if (response.data.code == 200) {
                            _this.tableData = response.data.data.list;
                            _this.total = response.data.data.total;
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            },
            //实行每页有多少条的方法
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
                this.pageSize = val;
                this.loadData();
            },
            //实现跳转页的方法
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.currentPage = val;
                this.loadData();
            },
            //刷新
            refresh() {
                //原始js重新请求
                location.reload();
            },
            //用户类型 把状态数字,转换成字符
            getStatus1(row, column, cellValue, index) {
                return cellValue == 0 ? "系统用户" : "非系统用户";
            },
            //用户性别 把状态数字,转换成字符
            getStatus2(row, column, cellValue, index) {
                return cellValue == 0 ? "男" : "女";
            },
            //帐号状态 把状态数字,转换成字符
            getStatus3(row, column, cellValue, index) {
                return cellValue == 0 ? "正常" : "停用";
            },
            //删除标志 把状态数字,转换成字符
            getStatus4(row, column, cellValue, index) {
                return cellValue == 0 ? "存在" : "删除";
            },
            //查询方法
            search() {
                this.loadData();
                //搜索时,使页码为1
                this.currentPage = 1;
            },
            //用户更新的方法
            handleEdit(index, row) {
                console.log(index, row);
                //使弹出框显示
                this.dialogFormVisible = true;
                //给用户赋值
                this.title = '用户更新';
                //点击查询携带数据
                this.form = row;
                //照片方法
                this.imageUrl= row.avatar;
            },
            //添加数据方法
            handleAdd() {
                //使弹出框显示
                this.dialogFormVisible = true;
                //给用户赋值
                this.title = '用户添加';
                //点击查询携带数据
                this.form = {}
                //照片方法
                this.imageUrl="";
            },
            //关闭方法
            handleClose(done) {
                this.$confirm('确认关闭？')
                    .then(_ => {
                        done();
                    })
                    .catch(_ => {
                    });
            },
            //删除方法
            deleteDept(row) {
                this.$confirm('此操作将删除该用户, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {
                    var _this = this;
                    axios.post("/user/delete/" + row.userId)
                        .then(function (response) {
                            console.log(response);
                            if (response.data.code == 200) {
                                _this.$message({
                                    message: '操作成功',
                                    type: 'success'
                                });
                                _this.dialogFormVisible = false;
                                _this.loadData();
                            } else {
                                _this.$message("操作失败")
                            }
                        })
                        .catch(function (error) {
                            console.log(error);
                        });
                })
            },

            //实现用户添加或者更新
            addOrUpdate() {
                var uri = "/user/add";
                if (this.title == '用户更新') {
                    uri = "/user/update";
                }
                var _this = this;
                axios.post(uri, this.form)
                    .then(function (response) {
                        console.log(response);
                        if (response.data.code == 200) {
                            _this.$message({
                                message: '操作成功',
                                type: 'success'
                            });
                            _this.dialogFormVisible = false;
                            _this.loadData();
                        } else {
                            _this.$message("操作失败")
                        }
                    })
                    .catch(function (error) {
                        console.log(error);
                    });
            },

            //获取所有角色
            getHaveRole() {
                var _this = this;
                // 使用axios向后台发请求
                axios.post("/role/queryPage",
                    {"pageNo": 1, "pageSize": 100})
                    .then(function (response) { //回调函数
                        console.log(response);//前端控制台打印
                        //response获取后台数据书，一定要加data,  response.data相当于从响应的body中获取数据
                        if (response.data.code == 200) {
                            _this.roleList = response.data.data.list;
                        } else {
                            _this.$message.error('执行失败');
                        }
                    })
                    .catch(function (error) {//异常处理
                        console.log(error);
                    });
            },

            //获取当前用户已经拥有的角色
            handleRole(index, row) {
                //定义变量
                tempUserId = row.userId;
                this.dialogVisible = true; //让对话框显示
                //定义变量
                tempUserId = row.userId;
                var _this = this;
                // 使用axios向后台发请求
                axios.get("/UserAndRole/queryByUserId?userId=" + row.userId).then(function (response) { //回调函数
                    console.log(response);//前端控制台打印，response是json对象
                    console.log(JSON.stringify(response));
                    //response获取后台数据书，一定要加data,  response.data相当于从响应的body中获取数据
                    if (response.data.code == 200) {
                        _this.checkedRoles = [];
                        for (var i = 0; i < response.data.data.length; i++) {
                            //把查询到的角色添加到集合里
                            _this.checkedRoles.push(response.data.data[i].roleId);
                            console.log(JSON.stringify(_this.checkedRoles));
                        }
                    } else {
                        _this.$message.error('执行失败');
                    }
                })
                    .catch(function (error) {//异常处理
                        console.log(error);
                    });
            },

            //给用户添加角色
            addUserAndRole() {
                var _this = this;
                var roleIdsArrray = this.roleIds.toString().split(",");
                //alert(roleIdsArrray);
                for (var i = 0; i < roleIdsArrray.length; i++) {
                    // 使用axios向后台发请求
                    axios.post("/UserAndRole/add",  //请求的url
                        {"userId": tempUserId, "roleId": roleIdsArrray[i]}
                    ) //请求的参数，json格式
                        .then(function (response) { //回调函数
                            //response获取后台数据书，一定要加data,  response.data相当于从响应的body中获取数据
                            if (response.data.code == 200) {
                                //提示成功
                                _this.$message({
                                    message: '执行成功',
                                    type: 'success'
                                });
                                //关闭弹框
                                _this.dialogVisible = false;
                            } else {
                                _this.$message.error('执行失败');
                            }
                        })
                        .catch(function (error) {//异常处理
                            console.log(error);
                        });
                }
            },

            //角色全选
            handleCheckAllChange(val) {
                this.checkedRoles = val ? roleList : [];
                this.isIndeterminate = false;
            },

            //勾选角色
            handleCheckedRolesChange(value) {
                this.roleIds = value; //把勾选的角色id赋值给roleIds
                alert( this.roleIds);
                let checkedCount = value.length;
                this.checkAll = checkedCount === this.roleList.length;
                this.isIndeterminate = checkedCount > 0 && checkedCount < this.roleList.length;
            },
            //处理文件成功后的处理方法
            handleFileSuccess(res, file) {
                //回显上传图片
                this.imageUrl = URL.createObjectURL(file.raw);
                this.form.avatar=file.response.data.filePath;
            },
            //处理文件成功前的处理方法
            beforeFileUpload(file) {
                const FILE_NAME = file.name;
                if (
                    FILE_NAME.substring(FILE_NAME.lastIndexOf(".")) !== ".bmp" &&
                    FILE_NAME.substring(FILE_NAME.lastIndexOf(".")) !== ".jpg" &&
                    FILE_NAME.substring(FILE_NAME.lastIndexOf(".")) !== ".png"
                ) {
                    this.$message.warning("仅支持.bmp.jpg.png文件");
                    return false;
                }
                // const isJPG = file.type === 'image/jpeg';
                const isLt6M = file.size / 1024 / 1024 < 6;
                // if (!isJPG) {
                //     this.$message.error('上传头像图片只能是 JPG 格式!');
                // }
                if (isLt6M) {
                    this.file = file;
                    return true;
                }
                this.$message.warning("请上传不超过6M的文件.");
                return false;
            },
        }
    })
</script>
</body>
</html>